const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

// 读取配置文件
function readConfig() {
    const configPath = path.join(__dirname, 'server_input.txt');
    try {
        if (fs.existsSync(configPath)) {
            const rawData = fs.readFileSync(configPath, 'utf8');
            console.log('[DEBUG] Raw config file content:', JSON.stringify(rawData));
            
            // 处理不同的换行符格式 (CRLF, LF, CR)
            const lines = rawData
                .replace(/\r\n/g, '\n')  // Windows CRLF -> LF
                .replace(/\r/g, '\n')    // Old Mac CR -> LF
                .split('\n')
                .map(line => line.trim()) // 移除每行的空白字符
                .filter(line => line.length > 0); // 移除空行
            
            console.log('[DEBUG] Parsed config lines:', lines);
            
            const deviceIndex = lines[0] || '3';
            const logLevel = lines[1] || 'info';
            
            console.log('[DEBUG] Final config - deviceIndex:', deviceIndex, 'logLevel:', logLevel);
            
            return {
                deviceIndex: deviceIndex,
                logLevel: logLevel
            };
        }
    } catch (error) {
        console.error('[ERROR] Could not read server_input.txt:', error.message);
        console.log('[INFO] Using default configuration');
    }
    return {
        deviceIndex: '3',
        logLevel: 'info'
    };
}

// 检查必需文件
function checkRequiredFiles() {
    const requiredFiles = ['server.js', 'package.json'];
    const missingFiles = [];
    
    for (const file of requiredFiles) {
        if (!fs.existsSync(path.join(__dirname, file))) {
            missingFiles.push(file);
        }
    }
    
    if (missingFiles.length > 0) {
        console.error('[ERROR] Missing required files:', missingFiles.join(', '));
        console.error('[SOLUTION] Ensure all project files are properly extracted');
        process.exit(1);
    }
    
    // 检查node_modules
    if (!fs.existsSync(path.join(__dirname, 'node_modules'))) {
        console.error('[ERROR] node_modules directory not found');
        console.error('[SOLUTION] Run install.bat first to install dependencies');
        process.exit(1);
    }
    
    console.log('[SUCCESS] All required files found');
}

// 执行检查
checkRequiredFiles();

const config = readConfig();
console.log('Starting server with automatic device selection...');
console.log(`Auto-selecting device ${config.deviceIndex} and log level ${config.logLevel}...`);

// Start the server process with better error handling
let server;
try {
    // 按用户要求仅使用根服务器
    server = spawn('node', ['server.js'], {
        stdio: ['pipe', 'pipe', 'pipe']
    });
    console.log('[SUCCESS] Server process started');
} catch (error) {
    console.error('[ERROR] Failed to start server process:', error.message);
    console.error('[SOLUTION] Check if Node.js is properly installed and accessible');
    process.exit(1);
}

// Send input automatically
// 监听服务器输出，在适当时机发送输入
let deviceSent = false;
let levelSent = false;
let inputTimeout = null;

// 添加超时保护机制，防止等待输入时卡住
const setupInputTimeout = () => {
    if (inputTimeout) clearTimeout(inputTimeout);
    inputTimeout = setTimeout(() => {
        if (!deviceSent || !levelSent) {
            console.log('[TIMEOUT] Input timeout detected, sending automatic inputs...');
            if (!deviceSent) {
                try {
                    console.log(`[FORCE] Sending device selection: ${config.deviceIndex}`);
                    server.stdin.write(config.deviceIndex + '\n');
                    deviceSent = true;
                } catch (error) {
                    console.error('[ERROR] Failed to send device selection:', error.message);
                }
            }
            if (!levelSent) {
                try {
                    console.log(`[FORCE] Sending log level: ${config.logLevel}`);
                    server.stdin.write(config.logLevel + '\n');
                    levelSent = true;
                } catch (error) {
                    console.error('[ERROR] Failed to send log level:', error.message);
                }
            }
        }
    }, 10000); // 10秒超时
};

// 启动超时保护
setupInputTimeout();

server.stdout.on('data', (data) => {
    const output = data.toString();
    process.stdout.write(data);
    
    // 检测到设备选择提示时发送设备编号
    if ((output.includes('Please enter the number of the device') || 
         output.includes('Please enter the number') ||
         output.includes('device used for packet capture')) && !deviceSent) {
        setTimeout(() => {
            console.log(`[AUTO] Sending device selection: ${config.deviceIndex}`);
            try {
                server.stdin.write(config.deviceIndex + '\n');
                deviceSent = true;
                // 清除超时，因为已经发送了设备选择
                if (deviceSent && levelSent && inputTimeout) {
                    clearTimeout(inputTimeout);
                }
            } catch (error) {
                console.error('[ERROR] Could not send device selection:', error.message);
                // 不要立即退出，尝试继续运行
            }
        }, 500);
    }
    
    // 检测到日志级别提示时发送日志级别
    if ((output.includes('Please enter log level') || 
         output.includes('log level (info|debug)') ||
         output.includes('enter log level')) && !levelSent) {
        setTimeout(() => {
            console.log(`[AUTO] Sending log level: ${config.logLevel}`);
            try {
                server.stdin.write(config.logLevel + '\n');
                levelSent = true;
                // 清除超时，因为已经发送了日志级别
                if (deviceSent && levelSent && inputTimeout) {
                    clearTimeout(inputTimeout);
                }
            } catch (error) {
                console.error('[ERROR] Could not send log level:', error.message);
                // 不要立即退出，尝试继续运行
            }
        }, 1000); // 增加延迟到1秒，确保设备选择完成
    }
    
    // 检测服务器是否成功启动
    if (output.includes('Web Server started at')) {
        console.log('[SUCCESS] Web server startup confirmed!');
    }
    
    // 检测是否有设备列表（表示server.js正在正常运行）
    if (output.includes('Welcome to use Damage Counter')) {
        console.log('[SUCCESS] Server initialization started');
    }
});

server.stderr.on('data', (data) => {
    const errorOutput = data.toString();
    process.stderr.write(data);
    
    // 检测常见错误
    if (errorOutput.includes('EADDRINUSE')) {
        console.error('[ERROR] Port 8989 is already in use');
        console.error('[SOLUTION] Close other applications using port 8989 or restart computer');
    }
    if (errorOutput.includes('EACCES')) {
        console.error('[ERROR] Permission denied');
        console.error('[SOLUTION] Run as administrator');
    }
    if (errorOutput.includes('Cannot find module')) {
        console.error('[ERROR] Missing dependencies');
        console.error('[SOLUTION] Run install.bat to install dependencies');
    }
});

server.on('close', (code) => {
    console.log(`[INFO] Server process exited with code ${code}`);
    if (code !== 0) {
        console.error('[ERROR] Server process crashed unexpectedly');
        console.error('[SOLUTIONS] Check the following:');
        console.error('  1. Node.js dependencies are properly installed');
        console.error('  2. No other application is using port 8989');
        console.error('  3. Run as administrator if needed');
        console.error('  4. Check Windows Defender/Antivirus settings');
    }
    process.exit(code);
});

server.on('error', (error) => {
    console.error('[ERROR] Server process error:', error.message);
    console.error('[SOLUTION] Check if Node.js is properly installed');
    process.exit(1);
});

// Handle SIGINT (Ctrl+C)
process.on('SIGINT', () => {
    console.log('[INFO] Stopping server...');
    if (server && !server.killed) {
        server.kill('SIGINT');
        setTimeout(() => {
            if (!server.killed) {
                console.log('[WARN] Force killing server...');
                server.kill('SIGKILL');
            }
        }, 5000);
    }
});

// Handle unexpected exits
process.on('uncaughtException', (error) => {
    console.error('[FATAL] Uncaught exception:', error.message);
    console.error('[DEBUG] Stack trace:', error.stack);
    process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('[FATAL] Unhandled rejection at:', promise, 'reason:', reason);
    process.exit(1);
});
